package gpio

import (
	log "github.com/sirupsen/logrus"
	"github.com/stianeikeland/go-rpio/v4"
	"os/exec"
	"strconv"
)

func Do(f func() error) error {
	// 初始化

	if err := rpio.Open(); err != nil {
		log.Fatal(err)
	}
	defer rpio.Close()
	return f()
}

func SetValue(group, num, value int) (string, error) {
	cmd := exec.Command("gpio_operate", "set_value", strconv.Itoa(group), strconv.Itoa(num), strconv.Itoa(value))
	if output, err := cmd.CombinedOutput(); err != nil {
		return "", err
	} else {
		return string(output), nil
	}
}

func GetValue(group, num int) (string, error) {
	cmd := exec.Command("gpio_operate", "get_value", strconv.Itoa(group), strconv.Itoa(num))
	if output, err := cmd.CombinedOutput(); err != nil {
		return "", err
	} else {
		return string(output), nil
	}
}

func SetDirection(group, num, direction int) (string, error) {
	cmd := exec.Command("gpio_operate", "set_direction", strconv.Itoa(group), strconv.Itoa(num), strconv.Itoa(direction))
	if output, err := cmd.CombinedOutput(); err != nil {
		return "", err
	} else {
		return string(output), nil
	}
}

func GetDirection(group, num int) (string, error) {
	cmd := exec.Command("gpio_operate", "set_direction", strconv.Itoa(group), strconv.Itoa(num))
	if output, err := cmd.CombinedOutput(); err != nil {
		return "", err
	} else {
		return string(output), nil
	}
}
